import os
import tornado
import tornado.options
from tornado.web import RequestHandler


class IndexHandler(RequestHandler):
    def get(self):
        cookie = self.get_secure_cookie("count")
        count = int(cookie) + 1 if cookie else 1
        self.set_secure_cookie("count", str(count))
        self.write(
            '<html><head><title>Cookie计数器</title></head>'
            '<body><h1>您已访问本页%d次。</h1>' % count +
            '</body></html>'
        )

class IndexHandler01(RequestHandler):
    def get(self):
        self.write('<html><head><title>被攻击的网站</title></head>'
        '<body><h1>此网站的图片链接被修改了</h1>'
        '<img alt="这应该是图片" src="http://127.0.0.1:8000/?f=9000/">'
        '</body></html>'
        )

#设置了跨站请求伪造保护的请求！
class IndexHandler02(RequestHandler):
    '''为浏览器设置了_xsrf的Cookie（注意此Cookie浏览器关闭时就会失效）
    为模板的表单中添加了一个隐藏的输入名为 _xsrf，其值为_xsrf的Cookie值
    '''
    def get(self):
        self.render("index3.html")

    #使用postmam 不能发送请求！'_xsrf' argument missing from POST
    def post(self):
        self.write("hello ggujio")


app = tornado.web.Application(
    [
        (r'^/$', IndexHandler),
        (r'/1',IndexHandler01),
        (r'/3',IndexHandler02),
    ],
    cookie_secret = "2hcicVu+TqShDpfsjMWQLZ0Mkq5NPEWSk9fi0zsSt3A=",
    #开启保护Tornado将拒绝请求参数中不包含正确的_xsrf值
    xsrf_cookies = True,
    template_path=os.path.join(os.path.dirname(os.path.dirname(__file__)), "templates"),
)
if __name__ == "__main__":
    tornado.options.parse_command_line()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()